

	//directive
	angular.module('ksr.directives',['ngResource'])
	.directive('match', function() {
        return {
            require: 'ngModel',
            restrict: 'A',
            scope: {
                match: '='
            },
            link: function(scope, elem, attrs, ctrl) {
                scope.$watch(function() {
                    return (ctrl.$pristine && angular.isUndefined(ctrl.$modelValue)) || scope.match === ctrl.$modelValue;
                }, function(currentValue) {
                    ctrl.$setValidity('match', currentValue);
                });
            }
        };
    })
	.directive('greaterThan', function() {
        return {
            require: 'ngModel',
            restrict: 'A',
            scope: {
                greaterThan: '='
            },
            link: function(scope, elem, attrs, ctrl) {
                scope.$watch(function() {
                	var isSkipValidate = angular.isUndefined(scope.greaterThan)
                						|| angular.isUndefined(ctrl.$modelValue)
                						|| isNaN(scope.greaterThan)
                						|| isNaN(ctrl.$modelValue);
                    return isSkipValidate || scope.greaterThan < ctrl.$modelValue;
                }, function(currentValue) {
                    ctrl.$setValidity('greaterThan', currentValue);
                });
            }
        };
    })
	.directive('ksrRatingDistribution', [function () {
		return {
			restrict: 'E',
			templateUrl: '/ksr/partials/rating-distribution-chart.htm',
			link: function (scope, element, attrs) {
				attrs.$observe('reviewNumbers',function(nums){
					var valueArray,total=0,value,maxReviewsInRating=0;
					scope.ratings=[];
					if (nums.length>0){
						valueArray=nums.split(",");
					} else {
						valueArray = [0,0,0,0,0]
					}
					//valueArray :[5starNum,4StarNum,3StarNum,2StarNum,1StarNum]
					for (var i = 0; i < 5; i++) {
						value = parseInt(valueArray[i]);
						value = (!isNaN(value))?value:0
						scope.ratings[i]={
							title:"star-"+(5-i),
							reviewNumForStr:value
						};
						total+=value;
						if(maxReviewsInRating<value)
							maxReviewsInRating=value;
					};
					
					for (var i = 0; i < scope.ratings.length; i++) {
						scope.ratings[i].reviewPercentageForStr = (total>0)?(100*scope.ratings[i].reviewNumForStr/total).toFixed(1):0;
						scope.ratings[i].barPercentageForStr = (maxReviewsInRating>0)?(100*scope.ratings[i].reviewNumForStr/maxReviewsInRating).toFixed(0):0;
					};
				})
			}
		};
	}])
	.directive('categoryList', ['ksrCacheSvc',function (ksrCacheSvc) {
		return {
			restrict: 'E',
			templateUrl: '/ksr/partials/business/category-list.tmpl',
			scope:{
				parentType:"@"
			},
			// replace:true,
			link: function (scope, element, attrs) {
				ksrCacheSvc.get("categoryList",true).then(function(data){
					console.log("attrs.parentType="+scope.parentType);
	    			scope.categoryList = data;
	    			if (scope.$parent[scope.parentType]&&scope.$parent[scope.parentType].categories){
		    			scope[scope.parentType]={};
		    			scope[scope.parentType].categories = scope.$parent[scope.parentType].categories;
		    			sumupCategories();
	    			}
		    	},function(err){

		    	})

				function sumupCategories(){
					scope.totalSelectedCategories=0;
					for (var i = 0; i < scope.categoryList.length; i++) {
						scope.categoryList[i].count = countForEachNode (scope.categoryList[i])
						scope.totalSelectedCategories += scope.categoryList[i].count;
					}
					console.log("total cates="+scope.totalSelectedCategories);
				}
				
				function countForEachNode (cate){
					var sum=0;
					if (cate.children.length>0){
						for (var i = 0; i < cate.children.length; i++) {
							sum += countForEachNode (cate.children[i])
						}
						
					} else {
						if (isCategorySelected(cate.id)){
							cate.selected = true;
							return 1;
						} else {
							cate.selected = false;
							return 0;
						}
					}
					cate.count = sum;
			//		console.log("name="+cate.name+", count="+sum);
					return sum;
				}
				
				function isCategorySelected(id){
					var selected =false;
					angular.forEach(scope[scope.parentType].categories,function(category,idx){
						if(id==category.id) {
							selected =true;
						}
					})
					return selected;
				};
				
				scope.updateSelectedCategories = function(cate){
					if (cate.selected){//add category to business 
						scope[scope.parentType].categories.push(cate);
					} else { //remove from business
						var removedIdx = -1;
						angular.forEach(scope[scope.parentType].categories,function(category,idx){
							if(cate.id==category.id) {
								removedIdx = idx;
							}
						})
						if (removedIdx>=0)
							scope[scope.parentType].categories.splice(removedIdx,1);
					}
					sumupCategories();
				}
			}
		};
	}])
	.directive('ksrRatingStars', [function () {
		return {
			restrict: 'E',
			link: function (scope, element, attrs) {
				attrs.$observe('rating',function(rating){
					var r = parseInt(rating),html;
					r=(!isNaN(r))?r:0;
					var star='<i class="icon-star"></i>',
					halfStar='<i class="icon-star-half-empty"></i>',
					emptyStar='<i class="icon-star-empty"></i>'
					if (r>95){
					   html=star+star+star+star+star;
					} else if (r>85){
					   html=star+star+star+star+halfStar;
					} else if (r>75){
					   html=star+star+star+star+emptyStar;
					} else if (r>65){
					   html=star+star+star+halfStar+emptyStar;
					} else if (r>55){
					   html=star+star+star+emptyStar+emptyStar;
					} else if (r>45){
					   html=star+star+halfStar+emptyStar+emptyStar;
					} else if (r>35){
					   html=star+star+emptyStar+emptyStar+emptyStar;
					} else if (r>25){
					   html=star+halfStar+emptyStar+emptyStar+emptyStar;
					} else if (r>15){
					   html=star+emptyStar+emptyStar+emptyStar+emptyStar;
					} else if (r>5){
					  html=halfStar+emptyStar+emptyStar+emptyStar+emptyStar;
					} else{
					   html=emptyStar+emptyStar+emptyStar+emptyStar+emptyStar;
					}
					element.html(html);
				})
			}
		};
	}])
    ;

